package cn.cdu.medical.service.impl;

import cn.cdu.basics.exception.BusinessException;
import cn.cdu.data.entity.User;
import cn.cdu.data.service.IUserService;
import cn.cdu.medical.dto.HealthVisualizationDTO;
import cn.cdu.medical.dto.UserInfoDTO;
import cn.cdu.medical.dto.DiseaseDTO;
import cn.cdu.medical.dto.VisitDTO;
import cn.cdu.medical.entity.MedicalRecord;
import cn.cdu.medical.repository.MedicalRecordMapper;
import cn.cdu.medical.service.HealthVisualizationService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.time.LocalDate;
import java.time.Period;
import java.time.ZoneId;
import java.util.Date;

@Slf4j
@Service
@Transactional
public class HealthVisualizationServiceImpl implements HealthVisualizationService {

    @Autowired
    private IUserService userService;

    @Autowired
    private MedicalRecordMapper medicalRecordMapper;

    @Override
    public HealthVisualizationDTO getHealthVisualization(String userId) {
        // 获取用户信息
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 构建返回数据
        HealthVisualizationDTO dto = new HealthVisualizationDTO();
        
        // 设置用户基本信息
        UserInfoDTO userInfo = new UserInfoDTO();
        BeanUtils.copyProperties(user, userInfo);
        // 计算年龄
        Date birth = user.getBirth();
        if (birth != null) {
            LocalDate birthLocalDate = birth.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            userInfo.setAge(Period.between(birthLocalDate, LocalDate.now()).getYears());
        }
        dto.setUserInfo(userInfo);

        // 获取疾病分布数据
        dto.setDiseases(getDiseaseDistribution(userId));

        // 获取就诊记录
        dto.setVisits(getVisitRecords(userId));

        return dto;
    }

    @Override
    public List<DiseaseDTO> getDiseaseDistribution(String userId) {
        // 查询用户的病历记录
        QueryWrapper<MedicalRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .orderByDesc("visit_time");
        List<MedicalRecord> records = medicalRecordMapper.selectList(queryWrapper);

        // 转换为疾病DTO
        return records.stream()
                .map(record -> {
                    DiseaseDTO disease = new DiseaseDTO();
                    disease.setName(record.getDiagnosisName());
                    disease.setPosition(record.getDeptName()); // 使用科室作为身体部位
                    disease.setDiagnosisDate(record.getVisitTime());
                    disease.setStatus(record.getStatus());
                    return disease;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<VisitDTO> getVisitRecords(String userId) {
        // 查询用户的病历记录
        QueryWrapper<MedicalRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .orderByDesc("visit_time");
        List<MedicalRecord> records = medicalRecordMapper.selectList(queryWrapper);

        // 转换为就诊记录DTO
        return records.stream()
                .map(record -> {
                    VisitDTO visit = new VisitDTO();
                    visit.setDeptName(record.getDeptName());
                    visit.setVisitType(record.getVisitType());
                    visit.setVisitTime(record.getVisitTime());
                    visit.setDiagnosisName(record.getDiagnosisName());
                    return visit;
                })
                .collect(Collectors.toList());
    }
} 